package com.rv.admin.delay;

import lombok.Getter;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


public class DelayTask<V> implements Delayed {


    /**
     * 任务值
     */
    private final V value;


    /**
     * 任务处理
     */
    private final DelayTaskHandler<V> handler;


    /**
     * 延时时间,单位ms
     */
    @Getter
    private final Long delayTime;


    private final Long waitTime;


    public DelayTask(V value, DelayTaskHandler<V> handler, Long delayTime) {
        this.value = value;
        this.handler = handler;
        this.delayTime = delayTime;
        this.waitTime = System.currentTimeMillis() + delayTime;
    }


    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(waitTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }


    /**
     * 任务处理
     */
    public void handle() {
        handler.handle(value);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.waitTime, ((DelayTask<?>) o).getDelayTime());
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        DelayTask<?> delayTask = (DelayTask<?>) o;
        return Objects.equals(value, delayTask.value) && Objects.equals(handler, delayTask.handler) && Objects.equals(delayTime, delayTask.delayTime) && Objects.equals(waitTime, delayTask.waitTime);
    }

    @Override
    public int hashCode() {
        return Objects.hash(value, handler, delayTime, waitTime);
    }
}
